import { defineStore } from "pinia";
import {
  createCustomerAttendAPI,
  createVisitRecordAPI,
  getConfigAPI,
  getProductDetailAPI,
  productListAPI,
  searchCustomerAttendAPI,
  searchInnerAttendAPI,
  getInternalFiledPartnerAPI,
  updateVisitAPI,
  uploadFileAPI,
  visitDetailsAPI,
  getOuterFiledPartnerAPI,
  getCommunicationStagesAPI
} from "@/services/orderVisit";

import {
  createDefaultVisitInfo,
  makeVisitInfoFromJson
} from "@/views/orderVisit/type";

const customerType = "customer";
const innerType = "inner";
export const useOrderVisitStore = defineStore("orderVisit", {
  state: () => ({
    alreadyInit: false,
    cacheCustomerList: [],
    cacheAdressList: [],
    cacheRecommendedList: [],
    customerAttendList: [],
    innerAttendList: [],
    //  customer: 客户 inner: 内部
    currentListType: "",
    currentCustomName: "",
    currentCustomId: "",
    bindGoodsCategory: {
      selectedCategorys: [],
      selectedProducts: []
    },
    categories: [],
    config: {},
    salesConfig: {},
    visitInfo: createDefaultVisitInfo(),
    tempSalesMateCustomerName: "",
    selfInfo: {},
    alreayMapVisitInfo: false,
    // 在跳转到人员列表，返回沟通列表时
    anchorAttender: false,
    outerFiledTemple: [],
    innerFiledTemple: [],
    //客户沟通环节
    customerCommunicationStages: [],
    //商机沟通环节
    businessOpportunityStages: []
    
  }),
  actions: {
    async getVisitDetailAction(scheduleId) {
      if (this.alreayMapVisitInfo) return;
      this.alreayMapVisitInfo = true;
      const data = await visitDetailsAPI(scheduleId);
      this.visitInfo = makeVisitInfoFromJson(data, scheduleId);


      this.customerAttendList = this.visitInfo.participantList.filter(
        v => v.contactId?.length > 0
      ).map(v => ({
        name: v.name,
        contactId: v.contactId,
        checked: true
      }));
      this.innerAttendList = this.visitInfo.participantList.filter(
        v => v.ssoUserId?.length > 0
      ).map(v => ({
        name: v.name,
        ssoUserId: v.ssoUserId,
        checked: true
      }));

      console.log("customerAttendList", this.customerAttendList);
      console.log("innerAttendList", this.innerAttendList);
    },

    async searchSelfInfoAction() {
      let userInfo = localStorage.getItem("yxt-userInfo");
      if (!userInfo) {
        // 登录一下app 原生 设置信息
        setTimeout(() => {
          this.searchSelfInfoAction();
        }, 1000);
        return;
      }
      userInfo = JSON.parse(userInfo);
      let name = userInfo.name;
      const list = await this.searchInnerAttendAction(name);
      console.log("searchInnerAttendAPI", list);
      if (list.length > 0) {
        this.selfInfo = list.filter(v => v.fullname === name)[0] || list[0];
        this.selfInfo.checked = true;
        let alreayAdd = this.innerAttendList.some(
          v => v.fullname === name || v.name === name
        );
        console.log("alreayAdd", alreayAdd, name);
        console.log("innerAttendList", this.innerAttendList);
        if (!alreayAdd) {
          this.innerAttendList.push(this.selfInfo);
        }
      }
    },

    async searchInnerAttendAction(e) {
      const data = await searchInnerAttendAPI(e);
      return data.datas;
    },

    async loadCustomerAttendAction(customerId) {
      this.getConfigAction();
      let { customerContacts, customerName } =
        await searchCustomerAttendAPI(customerId);

        // 为了后面的操作统一，这里将后台的id 映射为 contactId 
      customerContacts = customerContacts.map(v => ({
        ...v,
        contactId: v.id,
      }));
      this.currentCustomId = customerId;
      this.currentCustomName = name;
      this.customerAttendList = customerContacts || [];
    },

    async getCustomerCommunicationStagesAction(parameter = { type : 0 }) {
      const data = await getCommunicationStagesAPI(parameter);
      this.customerCommunicationStages = data.datas;
    },

    async getStagesAction(parameter = { type : 0, targetId : "" }) {
      const data = await getCommunicationStagesAPI(parameter);
      return data.datas;
    },

    async getConfigAction() {
      this.config = await getConfigAPI();
    },

    // productListAPI
    async getProductListAction(categoryId, data) {
      const resData = await productListAPI(categoryId, data);
      return resData;
    },

    async createCustomerAttendAction(parameter) {
      const data = await createCustomerAttendAPI(
        parameter,
        this.currentCustomId
      );
      data.checked = true;
      this.customerAttendList.push(data);
    },

    async createVisitRecordAction(parameter) {
      const data = await createVisitRecordAPI(parameter);
      return data;
    },

    async updateVisitRecordAction(parameter) {
      const data = await updateVisitAPI(parameter);
      return data;
    },

    async uploadFileAction(parameter) {
      const data = await uploadFileAPI(parameter);
      return data;
    },

    setCurrentType(type) {
      this.currentListType = type == 0 ? customerType : innerType;
    },

    addInnerAttendList(list) {
      const mergedArray = [...this.innerAttendList, ...list];
      this.innerAttendList = Array.from(
        new Map(
          mergedArray.map(item => [
            `${item.fullname}${item.name}-${item.ssoUserId}-${item.userId}`, // 组合字段作为键
            item
          ])
        ).values()
      );
    },

    removeListFromAttendList(list) {
      let ids = list.map(v => v.id);
      this.innerAttendList = this.innerAttendList.filter(
        item => ids.indexOf(item.id) === -1
      );
    },

    async getOuterFiledPartnerAction() {
      let arr = await getOuterFiledPartnerAPI();
      this.outerFiledTemple = arr.filter(field => {
        return field.fieldStatus !== 0;
      });
    },

    async getInternalFiledPartnerAction(e) {
      let arr = await getInternalFiledPartnerAPI(e);
      this.innerFiledTemple = arr.filter(field => {
        return field.fieldStatus !== 0;
      });
    }
  },

  getters: {
    // 展示参会人列表，根据当前type展示不同数据
    currentListData() {
      return this.currentListType === innerType
        ? this.innerAttendList
        : this.customerAttendList;
    },

    customerPositions() {
      return this.config.customerPosition || [];
    },
    customerRoles() {
      return this.config.customerRole || [];
    },
    internalPositions() {
      return this.config.internalPartnerPositions || [];
    },
  },

  persist: {
    enabled: true,
    pick: [
      "config",
      "salesConfig",
      "selfInfo",
      "cacheCustomerList",
      "cacheAdressList",
      "cacheRecommendedList",
      "customerCommunicationStages"
    ],
    key: "orderVisit",
    storage: localStorage
  }
});
